<template>
  <div id="app">
    <div class="header_con">
      <div class="header">
        <div class="welcome fl">欢迎来到美多商城!</div>
        <div class="fr">
          <div v-if="username" class="login_btn fl">
            欢迎您：<em>{{ username }}</em>
            <span>|</span>
            <a @click="logout">退出</a>
          </div>
          <div v-else class="login_btn fl">
            <a href="/login/">登录</a>
            <span>|</span>
            <a href="/register/">注册</a>
          </div>
          <div class="user_link fl">
            <span>|</span>
            <a href="/user/center/">用户中心</a>
            <span>|</span>
            <a href="/carts/">我的购物车</a>
            <span>|</span>
            <a href="/orders/">我的订单</a>
          </div>
        </div>
      </div>
    </div>

    <div class="search_bar clearfix">
      <a href="index.html" class="logo fl"><img src="/static/images/logo.png"></a>
      <div class="sub_page_name fl">|&nbsp;&nbsp;&nbsp;&nbsp;购物车</div>
      <form method="get" action="/search.html" class="search_con fr mt40">
        <input type="text" class="input_text fl" name="q" placeholder="搜索商品">
        <input type="submit" class="input_btn fr" name="" value="搜索">
      </form>
    </div>

    <div class="total_count">全部商品<em>{{total_count}}</em>件</div>
    <ul class="cart_list_th clearfix">
      <li class="col01">商品名称</li>
      <li class="col03">商品价格</li>
      <li class="col04">数量</li>
      <li class="col05">小计</li>
      <li class="col06">操作</li>
    </ul>
    <ul class="cart_list_td clearfix" v-for="(sku,index) in cart">
      <li class="col01"><input type="checkbox" name="" v-model="sku.selected" @change="update_selected(index)"></li>
      <li class="col02"><img :src="'http://127.0.0.1:8000'+sku.default_image_url"></li>
      <li class="col03">{{ sku.name }}</li>
      <li class="col05">{{ sku.price }}元</li>
      <li class="col06">
        <div class="num_add">
          <a @click="on_add(index)" class="add fl">+</a>
          <input v-model="sku.count" @focus="origin_input=sku.count" @blur="on_input(index)" type="text"
                 class="num_show fl">
          <a @click="on_minus(index)" class="minus fl">-</a>
        </div>
      </li>
      <li class="col07">{{sku.amount}}元</li>
      <li class="col08"><a @click="on_delete(index)">删除</a></li>
    </ul>

    <ul class="settlements">
      <li class="col01"><input type="checkbox" name="" @change="on_selected_all" v-model="selected_all"></li>
      <li class="col02">全选</li>
      <li class="col03">合计(不含运费)：<span>¥</span><em>{{total_selected_amount}}</em><br>共计<b>{{total_selected_count}}</b>件商品
      </li>
      <li class="col04"><a href="/place_order/">去结算</a></li>
    </ul>

    <div class="footer">
      <div class="foot_link">
        <a href="#">关于我们</a>
        <span>|</span>
        <a href="#">联系我们</a>
        <span>|</span>
        <a href="#">招聘人才</a>
        <span>|</span>
        <a href="#">友情链接</a>
      </div>
      <p>CopyRight © 2016 北京美多商业股份有限公司 All Rights Reserved</p>
      <p>电话：010-****888 京ICP备*******8号</p>
    </div>
  </div>
</template>

<script>
  export default {
    name: "Carts",
    data() {
      return {
        host,
        username: sessionStorage.username || localStorage.username,
        user_id: sessionStorage.user_id || localStorage.user_id,
        token: sessionStorage.token || localStorage.token,
        cart: [],
        total_selected_count: 0,
        origin_input: 0 // 用于记录手动输入前的值
      }
    },
    computed: {
      total_count: function () {
        var total = 0;
        for (var i = 0; i < this.cart.length; i++) {
          total += parseInt(this.cart[i].count);
          this.cart[i].amount = (parseFloat(this.cart[i].price) * parseFloat(this.cart[i].count)).toFixed(2);
        }
        return total;
      },
      total_selected_amount: function () {
        var total = 0;
        this.total_selected_count = 0;
        for (var i = 0; i < this.cart.length; i++) {
          if (this.cart[i].selected) {
            total += (parseFloat(this.cart[i].price) * parseFloat(this.cart[i].count));
            this.total_selected_count += parseInt(this.cart[i].count);
          }
        }
        return total.toFixed(2);
      },
      selected_all: function () {
        var selected = true;
        for (var i = 0; i < this.cart.length; i++) {
          if (this.cart[i].selected == false) {
            selected = false;
            break;
          }
        }
        return selected;
      }
    },
    mounted() {
      this.get_carts()
    },
    methods: {
      get_carts() {
        // 获取购物车数据
        this.axios.get(this.host + '/cart/', {
          headers: {
            'Authorization': 'JWT ' + this.token
          },
          responseType: 'json'
        })
          .then(response => {
            debugger
            this.cart = response.data.data;
            for (var i = 0; i < this.cart.length; i++) {
              this.cart[i].amount = (parseFloat(this.cart[i].price) * this.cart[i].count).toFixed(2);
            }
          })
          .catch(error => {
            console.log(error.response.data);
          })
      },
      // 退出
      logout: function () {
        sessionStorage.clear();
        localStorage.clear();
        location.href = '/login.html';
      },
      update_count_selected(sku_id, count, selected) {
        this.axios.put(this.host + '/cart/', {
          sku_id: sku_id,
          count: count,
          selected: selected
        }, {
          headers: {
            'Authorization': 'JWT ' + this.token
          },
          responseType: 'json',
        })
          .then(response => {
            this.get_carts()
          })
          .catch(error => {
            alert('修改购物车失败');
          })
      },
      on_input(index) {
        var val = parseInt(this.cart[index].count);
        if (isNaN(val) || val <= 0) {
          this.cart[index].count = this.origin_input;
        } else {
          // 更新购物车数据
          this.axios.put(this.host + '/cart/', {
            sku_id: this.cart[index].id,
            count: val,
            selected: this.cart[index].selected
          }, {
            headers: {
              'Authorization': 'JWT ' + this.token
            },
            responseType: 'json'
          })
            .then(response => {
              this.cart[index].count = response.data.count;
            })
            .catch(error => {
              if ('non_field_errors' in error.response.data) {
                alert(error.response.data.non_field_errors[0]);
              } else {
                alert('修改购物车失败');
              }
              console.log(error.response.data);
              this.cart[index].count = this.origin_input;
            })
        }
      },
      // 更新购物车数据
      update_count: function (index, count) {
        var sku_id = this.cart[index].id
        var count = count
        var selected = this.cart[index].selected
        this.update_count_selected(sku_id, count, selected)
      },
      // 更新购物车数据
      update_selected: function (index) {
        var sku_id = this.cart[index].id
        var count = this.cart[index].count
        var selected = this.cart[index].selected
        this.update_count_selected(sku_id, count, selected)
      },

      // 减少操作
      on_minus: function (index) {
        if (this.cart[index].count > 1) {
          var count = this.cart[index].count - 1;
          this.update_count(index, count);
        }
      },
      on_add: function (index) {
        var count = this.cart[index].count + 1;
        this.update_count(index, count);
      },


      // 购物车全选
      on_selected_all: function () {
        var selected = !this.selected_all;
        this.axios.patch(this.host + '/cart/', {
          selected:selected
        }, {
          responseType: 'json',
          headers: {
            'Authorization': 'JWT ' + this.token
          },
        })
          .then(response => {
            this.get_carts()
          })
          .catch(error => {
            console.log(error.response.data);
          })
      },

      // 删除购物车数据
      on_delete: function (index) {
        this.axios.delete(this.host + '/cart/', {
          data: {
            sku_id: this.cart[index].id
          },
          headers: {
            'Authorization': 'JWT ' + this.token
          },
          responseType: 'json',
        })
          .then(response => {
            this.cart.splice(index, 1);
          })
          .catch(error => {
            console.log(error.response.data);
          })
      },
    }
  }
</script>

<style scoped>

</style>
